<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    img {
      width: 100px;
    }
  </style>
</head>

<body>
  <input type="file" name="upload" multiple style="display: none;">
  <button>图片上传</button>
  <progress value="0" max="100"></progress>
  <img src="" alt="">
  <script>
    document.querySelector("button").onclick = function () {
      document.querySelector("input").click()
    }


    const extendNames = ["jpg", "gif", "png"]

    document.querySelector("input").onchange = function () {
      console.log(this.files[0])
      // 获取到上传的文件
      const uploadImg = this.files[0]

      // 获取扩展名
      const extName = uploadImg.name.substring(uploadImg.name.lastIndexOf(".") + 1)

      const isRight = extendNames.some(v => v === extName)
      if (!isRight) {
        alert(`图片格式不正确，只能是"jpg", "gif", "png"`)
        return;
      }
      console.log(extName);
      // 读取文件 使用阅读器
      const reader = new FileReader()
      // 读取文件的方式
      reader.readAsDataURL(uploadImg) // base64
      reader.onloadstart = function () {
        console.log("开始读取");
      }
      reader.onprogress = function (evt) {
        // evt.total //文件总大小
        // evt.loaded // 已读取的大小
        const current = (evt.loaded / evt.total) * 100
        console.log(current);
      }
      // 读取完成
      reader.onload = function () {
        // console.log(reader.result)
        // document.querySelector("img").src = reader.result
        console.log("读取完成");
      }
      // 读取结束（无论成功与失败）
      reader.onloadend = function () {
        console.log("读取结束")
      }
      // 上传中止
      // reader.onabort = function () {
      //   // console.log(reader.result)
      //   // document.querySelector("img").src = reader.result
      //   console.log("上传中止");
      // }
    }

    // 读取多个文件 
  </script>
</body>

</html>
